package com.dayuanit.dy17.atm.atmbackoffice.shiro;

import com.dayuanit.dy17.atm.atmbackoffice.entity.Role;
import com.dayuanit.dy17.atm.atmbackoffice.entity.User;
import com.dayuanit.dy17.atm.atmbackoffice.service.IRoleService;
import com.dayuanit.dy17.atm.atmbackoffice.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AtmRealm extends AuthorizingRealm {
    private static final String realmName = "AtmRealm";

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    /**
     * 授权 也就是角色和权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("-----------授权-------------");
        User user = (User)principalCollection.getPrimaryPrincipal();

        List<Role> roles = roleService.loadRoles(user.getId());

        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : roles) {
            simpleAuthorizationInfo.addRole(role.getRoleKey());
            System.out.println(">>>>" + role.getRoleKey());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证过程 也就是登录
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-----------认证------------");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;
        String username = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());

        User user = userService.login(username, password);
        return new SimpleAuthenticationInfo(user, password, getName());
    }

    @Override
    public String getName() {
        return realmName;
    }
}
